/**
 * API错误类
 * 用于标准化API错误处理
 */
class ApiError extends Error {
  constructor(statusCode, message, isOperational = true, stack = '') {
    super(message);
    this.statusCode = statusCode;
    this.isOperational = isOperational;
    if (stack) {
      this.stack = stack;
    } else {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

/**
 * 错误处理中间件
 * 用于统一处理API错误
 */
const errorHandler = (err, req, res, next) => {
  let error = err;
  
  // 如果不是ApiError实例，转换为ApiError
  if (!(error instanceof ApiError)) {
    const statusCode = error.statusCode || 500;
    const message = error.message || '服务器内部错误';
    error = new ApiError(statusCode, message, false, err.stack);
  }
  
  // 返回错误响应
  res.status(error.statusCode).json({
    success: false,
    message: error.message,
    ...(process.env.NODE_ENV === 'development' && { stack: error.stack })
  });
};

module.exports = {
  ApiError,
  errorHandler
}; 